﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Backend.JYD.Model.Task;
using Backend.JYD.Model;
using Backend.JYD.Cache;
using Backend.JYD.Common;
using Backend.JYD.Model.Auth;

namespace Backend.JYD.Business
{
    public class TaskManager
    {
        #region const

        private const Int64 TaskModel_TaskModelId = 1;
        private const string key_TaskStepModel = "TaskStepModel_All";
        private const string key_TaskModel = "TaskModel_All";

        #endregion

        #region DAL

        private static readonly IDAL.Task.ITaskBaseInfo baseDAL = Factory.DALFactory.CreateEFDAL<IDAL.Task.ITaskBaseInfo>("DAL.TaskBaseInfoDAL");
        private static readonly IDAL.Task.ITaskStepInfo stepDAL = Factory.DALFactory.CreateEFDAL<IDAL.Task.ITaskStepInfo>("DAL.TaskStepInfoDAL");

        private static readonly IDAL.Task.ITaskModel baseModelDAL = Factory.DALFactory.CreateEFDAL<IDAL.Task.ITaskModel>("DAL.TaskModelDAL");
        private static readonly IDAL.Task.ITaskStepModel stepModelDAL = Factory.DALFactory.CreateEFDAL<IDAL.Task.ITaskStepModel>("DAL.TaskStepModelDAL");

        private static readonly IDAL.IEmpRoleInfo empRoleDAL = Factory.DALFactory.CreateEFDAL<IDAL.IEmpRoleInfo>("DAL.EmpRoleInfoDAL");
        private static readonly IDAL.Task.IIntentEntryInfo intentEntryDAL = Factory.DALFactory.CreateEFDAL<IDAL.Task.IIntentEntryInfo>("DAL.IntentEntryInfoDAL");

        #endregion

        #region Enum Model

        public enum StepModelCode
        {
            HandOut = 1,
            Marketing = 2,
            Investigate = 3,
            Completion = 4,
            Audit = 5
        }
        /// <summary>
        /// 0-未处理；1-处理中；2-已完成，进入下一步；3-已退回；4-已完成，进入循环步骤；5-已结束-终止
        /// </summary>
        public enum TaskStatus
        {
            /// <summary>
            /// 0=未处理
            /// </summary>
            Beginning = 0,
            /// <summary>
            /// 1=处理中
            /// </summary>
            Processing = 1,
            /// <summary>
            /// 2=已完成，进入下一步
            /// </summary>
            CompleteAndReady = 2,
            /// <summary>
            /// 3=已退回
            /// </summary>
            ReturnToLast = 3,
            /// <summary>
            /// 4=已完成，进入循环步骤
            /// </summary>
            CompleteAndLoop = 4,
            /// <summary>
            /// 5=已结束-终止
            /// </summary>
            Complete = 5
        }

        public static string GetTaskStatusCode(int status)
        {
            switch (status)
            { 
                case (int)TaskStatus.Processing:
                    return "处理中";
                case (int)TaskStatus.Beginning:
                    return "未开始";
                case (int)TaskStatus.Complete:
                    return "任务已结束";
                case (int)TaskStatus.CompleteAndLoop:
                    return "循环执行";
                case (int)TaskStatus.CompleteAndReady:
                    return "已提交";
                case (int)TaskStatus.ReturnToLast:
                    return "已退回";
            }
            return string.Empty;
        }

        public static StepModelCode GetStepModelCodeByStepCode(string stepCode)
        {
            try
            {
                return (StepModelCode)Enum.Parse(typeof(StepModelCode), stepCode, true);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                throw ex;
            }
        }

        public static TaskStatus GetTaskStatusByStatusCode(string statusCode)
        {
            try
            {
                return (TaskStatus)Enum.Parse(typeof(TaskStatus), statusCode, true);
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                throw ex;
            }
        }

        #endregion

        #region TaskModel

        public static List<TaskModel> LoadAllTaskModeles()
        {
            var list = CacheMgr.Instance.GetCachedItem<List<TaskModel>>(key_TaskModel);
            if (list == null)
            {
                var temp = baseModelDAL.GetAllTaskModels();
                if (temp != null)
                {
                    CacheMgr.Instance.SetCachedItem<List<TaskModel>>(key_TaskModel, temp.ToList());
                }
            }
            return list;
        }

        public static void ReloadAllTaskModeles()
        {
            var list = baseModelDAL.GetAllTaskModels();
            if (list != null)
            {
                CacheMgr.Instance.SetCachedItem<IList<TaskModel>>(key_TaskModel, list);
            }
        }

        #endregion

        #region TaskStepModel
        public static List<TaskStepModel> LoadAllTaskStepModel()
        {
            return LoadAllTaskStepModel(TaskModel_TaskModelId);
        }
        public static List<TaskStepModel> LoadDefaultTaskStepModel()
        {
            return LoadAllTaskStepModel(TaskModel_TaskModelId);
        }
        public static List<TaskStepModel> LoadAllTaskStepModel(Int64 taskModelId)
        {
            string key = key_TaskStepModel + "_" + taskModelId;
            var list = CacheMgr.Instance.GetCachedItem<List<TaskStepModel>>(key);
            if (list == null)
            {
                var temp = stepModelDAL.GetTaskStepModelByTaskModeId(taskModelId);
                if (temp != null)
                {
                    list = temp.ToList();
                    CacheMgr.Instance.SetCachedItem<List<TaskStepModel>>(key, list);
                }
            }
            return list;
        }

        public static void ReloadAllTaskStepModeles(Int64 taskModelId)
        {
            string key = key_TaskStepModel + "_" + taskModelId;
            var list = stepModelDAL.GetTaskStepModelByTaskModeId(taskModelId);
            if (list != null)
            {
                CacheMgr.Instance.SetCachedItem<List<TaskStepModel>>(key, list.ToList());
            }
        }

        public static List<TaskStepModel> LoadTaskStepModelByTaskModeId(Int64 taskModelId)
        {
            string key = key_TaskStepModel + "_" + taskModelId;
            var list = CacheMgr.Instance.GetCachedItem<List<TaskStepModel>>(key);
            if (list == null)
            {
                var temp = TaskManager.LoadAllTaskStepModel(taskModelId);
                if (temp != null)
                {
                    list = temp.ToList();
                    CacheMgr.Instance.SetCachedItem<List<TaskStepModel>>(key, list);
                }
                else
                {
                    LogHelper.Info("加载模型出错，taskModelId=" + taskModelId);
                }
            }
            return list;
        }

        public static void ReloadTaskStepModelesByTaskModelId(Int64 taskModelId)
        {
            var list = stepModelDAL.GetTaskStepModelByTaskModeId(taskModelId);
            if (list != null)
            {
                string key = key_TaskStepModel + "_" + taskModelId;
                CacheMgr.Instance.SetCachedItem<List<TaskStepModel>>(key, list.ToList());
            }
        }

        #endregion

        #region Task

        public IntentEntryInfo CreateIntentTask(IntentEntryInfo info, string custNo)
        {
            var stepModels = TaskManager.LoadTaskStepModelByTaskModeId(TaskModel_TaskModelId);
            var first = stepModels.First();
            if (first == null) return info;
            var taskInfo = new TaskBaseInfo();
            taskInfo.CreateTime = DateTime.Now;
            taskInfo.OpId = info.OpId;
            taskInfo.Status = (int)TaskManager.TaskStatus.Beginning;
            taskInfo.TaskModelId = TaskModel_TaskModelId;
            taskInfo.TaskDetailId = 0;
            taskInfo.Type = 1;
            taskInfo.EmpIds = info.OpId.ToString();
            taskInfo.UpdateTime = DateTime.Now;
            taskInfo.StepId = first == null ? 0 : first.StepId;
            taskInfo.CustNo = custNo;
            taskInfo.IntentId = info.IntentId;
            taskInfo.CustName = info.CustName;
            taskInfo.Phone = info.Phone;
            
            Int64 taskId = baseDAL.AddTaskBaseInfo(taskInfo);
            if (taskId <= 0) return info;

            info.TaskId = taskId;


            var stepInfo = new TaskStepInfo()
            {
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Type = 1,
                OpId = info.OpId,
                EmpIds = info.OpId.ToString(),
                Status = 0,
                StepId = first.StepId,
                TaskId = taskId
            };
            var taskDetailId = stepDAL.AddTaskStepInfo(stepInfo);
            info.TaskDetailId = taskDetailId;
            taskInfo.TaskDetailId = taskDetailId;

            //intentEntryDAL.UpdateIntentEntryInfo(info);
            baseDAL.UpdateTaskBaseInfo(taskInfo);

            return info;
        }

        public bool BeginProcessStep(TaskStepInfo currStep)
        {
            currStep.Status = (int)TaskManager.TaskStatus.Processing;
            var taskBaseInfo = baseDAL.GetTaskBaseInfoByTaskId(currStep.TaskId);
            if (taskBaseInfo != null)
            {
                taskBaseInfo.Status = (int)TaskManager.TaskStatus.Processing;
                taskBaseInfo.OpId = currStep.OpId;

                stepDAL.UpdateTaskStepInfo(currStep);
                baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                return true;
            }
            return false;
        }

        public bool BeginProcessStep(Int64 taskId, Int64? opId, string remark)
        {
            var taskBaseInfo = baseDAL.GetTaskBaseInfoByTaskId(taskId);
            if (taskBaseInfo != null && taskBaseInfo.TaskDetailId.HasValue && taskBaseInfo.TaskDetailId.Value > 0)
            {
                var currStep = stepDAL.GetTaskStepInfoByTaskDetailId(taskBaseInfo.TaskDetailId.Value);
                if (currStep != null)
                {
                    currStep.Status = 1;
                    currStep.OpId = opId;
                    currStep.Remark = remark;

                    taskBaseInfo.Status = 1;
                    taskBaseInfo.OpId = opId;

                    stepDAL.UpdateTaskStepInfo(currStep);
                    baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 意向任务提交到下一步
        /// </summary>
        /// <param name="taskId"></param>
        /// <param name="remark"></param>
        /// <param name="opId"></param>
        /// <returns></returns>
        public bool IntentNextStep(Int64 taskId, string remark, Int64? opId)
        {
            var taskBaseInfo = baseDAL.GetTaskBaseInfoByTaskId(taskId);
            if (taskBaseInfo == null) return false;

            var stepModels = TaskManager.LoadTaskStepModelByTaskModeId(TaskModel_TaskModelId);
            if (stepModels == null) return false;

            var stepInfos = stepDAL.GetTaskStepInfoByTaskId(taskId);
            if (stepInfos == null) return false;


            var currStep = stepInfos.First();
            if (currStep != null && stepModels != null)
            {
                currStep.UpdateTime = DateTime.Now;
                currStep.Remark = remark;

                var currModel = stepModels.Find(p => p.StepId == currStep.StepId);
                if (currModel != null)
                {
                    if (currModel.UseRole)
                    {
                        currStep.RoleIds = this.NextOperatorStrategy(currModel);
                    }
                    else
                    {
                        currStep.EmpIds = this.NextOperatorStrategy(currModel);
                    }

                    TaskStepModel nextModel = null;
                    TaskStepInfo nextStep = new TaskStepInfo();
                    nextStep.Status = (int)TaskManager.TaskStatus.Beginning;
                    nextStep.Type = 1;
                    nextStep.OpId = currStep.OpId;
                    nextStep.UpdateTime = DateTime.Now;
                    nextStep.CreateTime = DateTime.Now;
                    nextStep.TaskId = taskId;

                    var nextStepIds = StringHelper.String2List<Int32>(currModel.NextStepIds);
                    if (nextStepIds == null || nextStepIds.Count <= 0) return false;

                    nextModel = stepModels.Find(p => p.StepId == nextStepIds.First());
                    if (nextModel != null)
                    {
                        if (nextModel.UseRole)
                        {
                            nextStep.RoleIds = nextModel.RoleIds;
                        }
                        else
                        {
                            nextStep.EmpIds = nextModel.EmpIds;
                        }
                        nextStep.StepId = nextStepIds.First();

                        currStep.Status = (int)TaskManager.TaskStatus.CompleteAndReady;
                    }
                    else
                    {
                        currStep.Status = (int)TaskManager.TaskStatus.Complete;
                    }

                    #region 保存操作

                    taskBaseInfo.UpdateTime = DateTime.Now;
                    taskBaseInfo.Status = currStep.Status;

                    if (currStep.Status == (int)TaskManager.TaskStatus.Complete)
                    {
                        stepDAL.UpdateTaskStepInfo(currStep);
                        baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                    }
                    else
                    {
                        stepDAL.UpdateTaskStepInfo(currStep);
                        baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                        Int64 detailId = stepDAL.AddTaskStepInfo(nextStep);

                        taskBaseInfo.Status = nextStep.Status;
                        taskBaseInfo.UpdateTime = DateTime.Now;
                        taskBaseInfo.EmpIds = nextStep.EmpIds;
                        taskBaseInfo.RoleIds = nextStep.RoleIds;
                        taskBaseInfo.TaskDetailId = detailId;
                        taskBaseInfo.StepId = nextStep.StepId;
                        baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                    }

                    #endregion
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 任务操作
        /// 终止、循环 操作只提供taskId，remark，opId。
        /// </summary>
        /// <param name="taskId">必需：任务编号</param>
        /// <param name="chkIds">下一步 操作必需(RoleIds or EmpIds)</param>
        /// <param name="nextStatus">必需</param>
        /// <param name="nextStepId">返回, 下一步 操作必需</param>
        /// <param name="remark"></param>
        /// <param name="opId"></param>
        /// <returns></returns>
        public bool NextStep(Int64 taskId, List<Int64> chkIds, TaskManager.TaskStatus nextStatus, Int32? nextStepId, string remark, Int64? opId)//TaskStepInfo
        {
            #region 数据准备
            
            var taskBaseInfo = baseDAL.GetTaskBaseInfoByTaskId(taskId);
            if (taskBaseInfo == null) return false;

            var stepModels = TaskManager.LoadTaskStepModelByTaskModeId(taskBaseInfo.TaskModelId);
            if (stepModels == null) return false;

            var stepInfos = stepDAL.GetTaskStepInfoByTaskId(taskId);
            if (stepInfos == null) return false;

            #endregion

            var currStep = stepInfos.ToList().Find(p => p.TaskDetailId == taskBaseInfo.TaskDetailId);
            if (currStep != null && stepModels != null)
            {
                currStep.UpdateTime = DateTime.Now;
                currStep.Remark = remark;
                currStep.OpId = opId;

                var currModel = stepModels.ToList().Find(p => p.StepId == currStep.StepId);
                if (currModel != null)
                {
                    TaskStepModel nextModel = null;
                    TaskStepInfo nextStep = new TaskStepInfo();
                    nextStep.Status = (int)TaskManager.TaskStatus.Beginning;
                    nextStep.Type = 1;
                    nextStep.OpId = currStep.OpId;
                    nextStep.UpdateTime = DateTime.Now;
                    nextStep.CreateTime = DateTime.Now;
                    nextStep.TaskId = taskId;

                    #region 初始化数据

                    if (nextStatus == TaskManager.TaskStatus.Complete)
                    {
                        currStep.Status = (int)TaskManager.TaskStatus.Complete;
                    }
                    else if (nextStatus == TaskManager.TaskStatus.CompleteAndLoop)
                    {
                        #region CompleteAndLoop
                        
                        if (currModel.AllowLoop)
                        {
                            nextStep.EmpIds = currStep.EmpIds;
                            nextStep.RoleIds = currStep.RoleIds;
                            nextStep.StepId = currStep.StepId;

                            currStep.Status = (int)TaskManager.TaskStatus.CompleteAndLoop;
                        }
                        else
                        {
                            currStep.Status = (int)TaskManager.TaskStatus.Complete;
                        }

                        #endregion
                    }
                    else if (nextStatus == TaskManager.TaskStatus.ReturnToLast)
                    {
                        #region ReturnToLast

                        if (!nextStepId.HasValue) return false;

                        var nextStepIds = StringHelper.String2List<Int32>(currModel.LastStepIds);
                        if (nextStepIds == null || nextStepIds.Count <= 0 || !nextStepIds.Contains(nextStepId.Value)) return false;

                        var lastStep = stepInfos.Count >= 1 ? stepInfos[1] : null;
                        if (lastStep != null)
                        {
                            nextStep.EmpIds = lastStep.EmpIds;
                            nextStep.RoleIds = lastStep.RoleIds;
                            nextStep.StepId = lastStep.StepId;
                        }
                        //nextModel即为lastModel
                        nextModel = stepModels.Find(p => p.StepId == nextStepId.Value);
                        if (nextModel != null)
                        {
                            currStep.Status = (int)TaskManager.TaskStatus.ReturnToLast;
                        }
                        else
                        {
                            currStep.Status = (int)TaskManager.TaskStatus.Complete;
                        }
                        #endregion
                    }
                    else if (nextStatus == TaskManager.TaskStatus.CompleteAndReady)
                    {
                        #region CompleteAndReady

                        if (!nextStepId.HasValue) return false;

                        var nextStepIds = StringHelper.String2List<Int32>(currModel.NextStepIds);
                        if (nextStepIds == null || nextStepIds.Count <= 0 || !nextStepIds.Contains(nextStepId.Value)) return false;

                        nextModel = stepModels.Find(p => p.StepId == nextStepId.Value);
                        if (nextModel != null)
                        {
                            currStep.Status = (int)TaskManager.TaskStatus.CompleteAndReady;
                        }
                        else
                        {
                            currStep.Status = (int)TaskManager.TaskStatus.Complete;
                        }

                        var nextChkIds = StringHelper.String2List<Int64>(nextModel.UseRole ? nextModel.RoleIds : nextModel.EmpIds);
                        if (chkIds == null)
                        {
                            chkIds = nextChkIds;
                        }
                        else
                        {
                            chkIds = chkIds.FindAll(p => nextChkIds.Contains(p));
                            if (chkIds == null || chkIds.Count <= 0) return false;
                        }

                        if (nextModel.UseRole)
                        {
                            nextStep.RoleIds = StringHelper.List2String<Int64>(chkIds, ",");
                        }
                        else
                        {
                            nextStep.EmpIds = StringHelper.List2String<Int64>(chkIds, ",");
                        }
                        nextStep.StepId = nextStepId.Value;

                        #endregion
                    }

                    #endregion

                    //对应操作的必需完成的验证？？

                    #region 保存操作

                    taskBaseInfo.UpdateTime = DateTime.Now;
                    taskBaseInfo.OpId = opId;
                    taskBaseInfo.Status = currStep.Status;
                    
                    if (currStep.Status == (int)TaskManager.TaskStatus.Complete)
                    {
                        stepDAL.UpdateTaskStepInfo(currStep);
                        baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                    }
                    else
                    {
                        stepDAL.UpdateTaskStepInfo(currStep);
                        baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                        Int64 detailId = stepDAL.AddTaskStepInfo(nextStep);

                        taskBaseInfo.Status = nextStep.Status;
                        taskBaseInfo.UpdateTime = DateTime.Now;
                        taskBaseInfo.EmpIds = nextStep.EmpIds;
                        taskBaseInfo.RoleIds = nextStep.RoleIds;
                        taskBaseInfo.TaskDetailId = detailId;
                        taskBaseInfo.StepId = nextStep.StepId;
                        baseDAL.UpdateTaskBaseInfo(taskBaseInfo);
                    }

                    #endregion
                    return true;
                }
                else
                {
                    //出错了。流程结束。
                }
            }
            return false;
        }

        public string NextOperatorStrategy(TaskStepModel model)
        {
            if (model.UseRole)
            {
                //return model.RoleIds.Split(',').First();
                return model.RoleIds;
            }
            else
            {
                //return model.EmpIds.Split(',').First();
                return model.EmpIds;
            }
        }

        #endregion

        #region function

        public string GetEmpIds(TaskStepModel model)
        {
            if (model == null) return string.Empty;
            if (model.UseRole)
            {
                var empInfos = empRoleDAL.GetEmpRoleInfoByRoleIds(model.RoleIds);
                if (empInfos.FirstOrDefault() != null)
                    return empInfos.FirstOrDefault().EmpId.ToString();

                return string.Empty;
                //string ids = string.Empty;
                //if (empInfos == null) return ids;
                //empInfos.ToList().ForEach(p => { if (p != null && p.EmpId > 0) { ids += p.EmpId + ","; } });
                //return ids;
            }
            else
            {
                return model.EmpIds.Split(',').First();
            }
        }

        public bool ContantId(string val, string id)
        {
            if (string.IsNullOrWhiteSpace(val) || string.IsNullOrWhiteSpace(id)) return false;
            return ("," + val + ",").Contains(id);
        }

        #endregion

        #region CheckTaskStepModel
        
        public bool CheckTaskStepModel(TaskBaseInfo info, StepModelCode? stepModelCode, TaskStatus? nextStatus)
        {
            var modeles = TaskManager.LoadTaskStepModelByTaskModeId(info.TaskModelId);
            if (modeles == null) return false;

            var model = modeles.Find(p => p.StepId == info.StepId);
            if (model == null) return false;

            return this.CheckTaskStepModel(info, model, stepModelCode, nextStatus);
        }
        public bool CheckTaskStepModel(TaskBaseInfo info,TaskStepModel model, StepModelCode? stepModelCode, TaskStatus? nextStatus)
        {
            if (stepModelCode == StepModelCode.HandOut)
            {
                return (info.Status == (int)TaskStatus.Beginning || info.Status == (int)TaskStatus.Processing)
                    && model != null && !string.IsNullOrWhiteSpace(model.NextStepIds)
                    && ((model.UseRole && !string.IsNullOrWhiteSpace(model.RoleIds)) || !string.IsNullOrWhiteSpace(model.EmpIds));
            }
            else if (stepModelCode == StepModelCode.Marketing)
            {
                //营销任务，在营销处理中提交，不能在任务步骤中处理
                return false;
            }
            else if (nextStatus.HasValue)
            {
                if (info.Status == (int)TaskStatus.Beginning && nextStatus.Value == TaskStatus.Processing)
                {
                    return model.StepCode.ToLower() != StepModelCode.HandOut.ToString().ToLower() && model.StepCode.ToLower() != StepModelCode.Marketing.ToString().ToLower();
                }
                else if ((info.Status == (int)TaskStatus.Beginning || info.Status == (int)TaskStatus.Processing))
                {
                    if (nextStatus.Value == TaskStatus.ReturnToLast)
                    {
                        return !string.IsNullOrWhiteSpace(model.LastStepIds);
                    }
                    else if (nextStatus.Value == TaskStatus.CompleteAndLoop)
                    {
                        return model.AllowLoop;
                    }
                    else if (nextStatus.Value == TaskStatus.CompleteAndReady && ((model.UseRole && string.IsNullOrWhiteSpace(model.RoleIds)) || (!model.UseRole && string.IsNullOrWhiteSpace(model.EmpIds))))
                    {
                        return !string.IsNullOrWhiteSpace(model.NextStepIds);
                    }
                    else if (nextStatus.Value == TaskStatus.Complete)
                    {
                        return model.AllowStop;
                    }
                }
            }
            return false;
        }

        #endregion

        #region 任务可操作控制

        public TaskOperationControl CheckTaskOperation(TaskBaseInfo info, TaskStepModel step, List<AuthorityInfo> authorityInfoes)
        {
            var opreation = new TaskOperationControl();

            if (step == null) return opreation;

            if (info.Status == (int)TaskManager.TaskStatus.Beginning)
            {
                if (step.StepCode.ToLower() == TaskManager.StepModelCode.HandOut.ToString().ToLower() && authorityInfoes != null)
                {
                    opreation.AllowBeginHandout = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskHandOut || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Marketing.ToString().ToLower() && authorityInfoes != null)
                {
                    opreation.AllowBeginMarketing = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskMarketing || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Investigate.ToString().ToLower() && authorityInfoes != null)
                {
                    opreation.AllowBeginInvestigate = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskInvestigate || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Completion.ToString().ToLower() && authorityInfoes != null)
                {
                    opreation.AllowBeginCompletion = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskCompletion || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Audit.ToString().ToLower() && authorityInfoes != null)
                {
                    opreation.AllowBeginAudit = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskAudit || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else
                {
                    opreation.AllowBeginProcess = true;
                }
            }
            else if (info.Status == (int)TaskManager.TaskStatus.Processing)
            {
                if (step.StepCode.ToLower() == TaskManager.StepModelCode.Marketing.ToString().ToLower())
                {
                    opreation.AllowProcessMarketing = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskMarketing || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.HandOut.ToString().ToLower())
                {
                    opreation.AllowProcessHandOut = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskHandOut || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Investigate.ToString().ToLower())
                {
                    opreation.AllowProcessInvestigate = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskInvestigate || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Completion.ToString().ToLower())
                {
                    opreation.AllowProcessCompletion = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskCompletion || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else if (step.StepCode.ToLower() == TaskManager.StepModelCode.Audit.ToString().ToLower())
                {
                    opreation.AllowProcessAudit = authorityInfoes.Exists(p => p.Code == AuthorCode.AuthorCode_TaskAudit || p.Code == AuthorCode.AuthorCode_TaskManager);
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(step.LastStepIds))
                    {
                        opreation.AllowProcessReturnToLast = true;
                    }
                    if (step.AllowLoop)
                    {
                        opreation.AllowProcessCompleteAndLoop = true;
                    }
                    if (!string.IsNullOrWhiteSpace(step.NextStepIds))
                    {
                        opreation.AllowProcessCompleteAndReady = true;
                    }
                    if (step.AllowStop)
                    {
                        opreation.AllowProcessComplete = true;
                    }
                }
            }
            return opreation;
        }

        #endregion
    }
}
